<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>索赔记录</title>
    <script type="text/javascript">
      var newClaimWin;
      var editClaimWin;
      
      var claimId;
      var newReturnedForClaimWin;
      var currentOrderNumber;//当前正操作的采购单单号
      Ext.onReady(function(){
        //所有物流公司
        var logisticsTemplate = new Ext.XTemplate('<tpl for="."><div class="search-item">', '<div style="float:left; width:45px">{number}</div>|{name}', '</div></tpl>');
        var logisticsStore = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: "/logistics/getAllLogistics?for_cbb=true"
          }),
          reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'number'
            }, {
              name: 'name'
            }, {
              name: 'linkman'
            }, {
              name: 'phone'
            }, {
              name: 'address'
            }])
        });

        var logistics = new Ext.form.ComboBox({
          store: logisticsStore,
          fieldLabel: '物流公司',
          allowBlank: false,
          blankText: "物流公司必须选择",
          emptyText: '请选择...',
          valueField: 'id',
          displayField: 'name',
          hiddenName: 'logistics_id',
          //typeAhead: false,
          loadingText: '搜索中...',
          anchor: '90%',
          //pageSize: 25,
          //hideTrigger: false,
          tpl: logisticsTemplate,
          minChars: 0,
          itemSelector: 'div.search-item',
          selectOnFocus:true
        });
        
        var purchaseOrderNumber = new Ext.form.TextField({
          fieldLabel: '采购单号',
          name: 'purchase_order_number'
        });

        var claimOrderNumber = new Ext.form.TextField({
          fieldLabel: '索赔单号',
          name: 'claim_order_number'
        });
        

        var stateStore = new Ext.data.ArrayStore({
          fields: ['text','value'],
          data : auditStatusArray
        });
        
        var auditingStatus = new Ext.form.ComboBox({
          fieldLabel: '审批状态',
          store: stateStore,
          displayField:'text',
          typeAhead: true,
          mode: 'local',
          name: 'auditing_status',
          forceSelection: true,
          triggerAction: 'all',
          editable:false,
          valueField: 'value',
          emptyText:'',
          anchor: '90%',
          selectOnFocus:true
        })

        var beginDate = new Ext.form.DateField({
          fieldLabel: '到货日期',
          name: 'begin_date',
          id: 'begin_date',
          format: 'Y-m-d', //格式化日期
          //disabledDays: [0,6],	//不让选择周六，周日
          //disabledDaysText: "周末要休息",
          invalidText: "您输入的日期格式不对，正确格式为2010-01-01",
          inputType: '2010-01-01',
          anchor: '90%',
          vtype: 'daterange',
          endDateField: 'end_date',
          listeners: {
            select: function(field, e){
              //Ext.MessageBox.alert('提示', '提交成功');
            }
          }
        });
        
        var endDate = new Ext.form.DateField({
          fieldLabel: '至    ',
          name: 'end_date',
          id: 'end_date',
          format: 'Y-m-d', //格式化日期
          //disabledDays: [0,6],	//不让选择周六，周日
          //disabledDaysText: "周末要休息",
          invalidText: "您输入的日期格式不对，正确格式为2010-01-01",
          inputType: '2010-01-01',
          anchor: '90%',
          vtype: 'daterange',
          startDateField: 'begin_date'
        });

        var submitButton = new Ext.Button({
          text: '搜索',
          iconCls: 'finding',
          handler: function(){
            claimDS.removeAll();
            claimDS.baseParams.purchase_order_number = purchaseOrderNumber.getValue();
            claimDS.baseParams.claim_order_number = claimOrderNumber.getValue();
            claimDS.baseParams.auditing_status = auditingStatus.getValue();

            claimDS.baseParams.begin_date = beginDate.getRawValue();
            claimDS.baseParams.end_date = endDate.getRawValue();
            claimDS.baseParams.logistics_id = logistics.getValue();
            claimDS.load();
          }
        });

        var clearButton = new Ext.Button({
          text: '清空',
          width:50,
          handler: function(){ 
            queryFormPanel.form.reset();
          }
        });

        var queryFormPanel = new Ext.form.FormPanel({
          //baseCls: 'x-plain',
          //renderTo: 'query_form',
          labelWidth: 65,
          width: screenWidth-175,
          labelAlign: 'right',
          frame : true,
          border:false,
          items: [{
              xtype: 'fieldset',
              defaults: {width: 1200},
              title: '查询条件',
              border: true,
              items: [{
                  layout: 'column',
                  border: false,
                  items: [{
                      columnWidth: .2,
                      layout: 'form',
                      border: false,
                      items: [purchaseOrderNumber]
                    }, {
                      columnWidth: .2,
                      layout: 'form',
                      border: false,
                      items: [auditingStatus]
                    }, {
                      columnWidth: .2,
                      layout: 'form',
                      border: false,
                      items: [logistics]
                    }]
                },{
                  layout: 'column',
                  border: false,
                  items: [{
                      columnWidth: .2,
                      layout: 'form',
                      border: false,
                      items: [claimOrderNumber]
                    },{
                      columnWidth: .2,
                      layout: 'form',
                      border: false,
                      items: [beginDate]
                    }, {
                      columnWidth: .2,
                      layout: 'form',
                      border: false,
                      items: [endDate]
                    }, {
                      columnWidth: .15,
                      layout: 'form',
                      border: false,
                      items: [submitButton]
                    }, {
                      columnWidth: .15,
                      layout: 'form',
                      border: false,
                      items: [clearButton]
                    }]
                }]
            }]
        });
        //显示索赔操作时的窗口介面。
        //----------------------------------索赔Grid-------------------------
        //索赔Grid Store
        var claimDS = new Ext.data.Store({
          paramNames: {
            start: "start",
            limit: "limit"
          },
          baseParams: {
            start: 0,
            limit: pageSize
          },
          proxy: new Ext.data.HttpProxy({
            url: '/claim/getAllClaims'
          }),
          reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'purchase_order_number',
              mapping:'purchase_order.order_number'
            },{
              name: 'entry_order_number',
              mapping:'warehousing_entry.order_number'
            },{
              name: 'order_number'
            }, {
              name: 'action_date'
            }, {
              name: 'amount',
              type: 'float'
            }, {
              name: 'description'
            }, {
              name: 'auditing_status'
            }, {
              name: 'audit_opinion'
            },{
              name: 'auditor_name',
              mapping:'auditor',
              convert:function(value,record){
                if(value == ""){
                  return "";
                }else{
                  return value.name;
                }
              }
            }, {
              name: 'logistics_name',
              mapping:'logistics.name'
            }, {
              name: 'department_name',
              mapping:'department.name'
            }, {
              name: 'employee_name',
              mapping:'employee.name'
            }, {
              name: 'deal_with_status'
            }, {
              name: 'store_status'
            }, {
              name: 'created_at'
            }, {
              name: 'updated_at'
            }])
        });
        
        //生成索赔Grid的CM
        var claimSM = new Ext.grid.CheckboxSelectionModel({singleSelect:true});
        var claimCM = new Ext.grid.ColumnModel({defaults: {
            sortable: true,
            menuDisabled: false
          },columns:[new Ext.grid.RowNumberer(),claimSM,{
              id: 'common',
              header: 'DB',
              dataIndex: 'id',
              width: 50
            },{
              header: '采购单号',
              dataIndex: 'purchase_order_number',
              width: 130
            },{
              header: '入库单号',
              dataIndex: 'entry_order_number',
              width: 120
            },{
              header: '索赔单号',
              dataIndex: 'order_number',
              width: 120
            },{
              header: '物流公司',
              dataIndex: 'logistics_name',
              width: 150
            },{
              header: '总金额',
              dataIndex: 'amount',
              align: 'right',
              renderer: Ext.util.Format.numberRenderer('0,000.00'),
              width: 75
            },{
              header: '索赔日期',
              dataIndex: 'action_date',
              renderer: Ext.util.Format.dateRenderer('Y-m-d'),
              width: 75
            },{
              header: '操作员',
              dataIndex: 'employee_name',
              width: 60
            },{
              header: '部门',
              dataIndex: 'department_name',
              width: 70
            },{
              header: '审批状态',
              dataIndex: 'auditing_status',
              width: 60,
              renderer: auditingStatusRender
            },{
              header: '审批者',
              dataIndex: 'auditor_name',
              width: 55
            },{
              header: '审批意见',
              dataIndex: 'audit_opinion',
              width: 150
            },{
              header: '处理状态',
              dataIndex: 'deal_with_status',
              renderer: dealWithStatusRender,
              width: 70
            },{
              header: '入库状态',
              dataIndex: 'store_status',
              renderer: dealWithStatusRender,
              width: 70
            },{
              header: '生成日期',
              dataIndex: 'created_at',
              renderer: Ext.util.Format.dateRenderer('Y-m-d H:i'),
              width: 100
            },{
              header: '修改日期',
              dataIndex: 'updated_at',
              renderer: Ext.util.Format.dateRenderer('Y-m-d H:i'),
              width: 100
            }
          ]});

        //生成要订单的产品的Grid
        var claimGrid = new Ext.grid.GridPanel({
          title:'索赔列表',
          store: claimDS,
          cm: claimCM,
          sm: claimSM,
          loadMask: true,
          width: screenWidth-175,
          height: 345,
          frame: true,
          //title: '进货品种列表',
          //plain:true,
          //plugins: checkColumn,
          bbar: new Ext.PagingToolbar({
            pageSize: pageSize,
            store: claimDS,
            displayInfo: true,
            displayMsg: "显示第 {0} 条到 {1} 条记录，一共 {2} 条",
            emptyMsg: "没有记录"
          }),
          tbar: [{
              text: '编辑',
              iconCls: 'editItem',
              handler : function(){
                var records = claimGrid.getSelectionModel().getSelections();
                if(records.length==0){
                  Ext.MessageBox.show({
                    title: '提示信息',
                    msg: "请先选中一条记录后，再编辑。",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.WARNING
                  });
                }else{
                  claimId = records[0].get('id');
                  if(records[0].get('auditing_status') != '通过' && records[0].get('auditing_status').indexOf('申请') < 0 && records[0].get('deal_with_status') != '撤消'){
                    editClaimWin = new Ext.Window({
                      layout: 'fit',
                      width: 917,
                      height: 483,
                      closeAction: 'destroy',
                      plain: true,
                      modal: true,
                      constrain:true,
                      //modal: true,
                      title: '编辑索赔',
                      autoLoad: {
                        url: "/claim/editClaimFromEntry?id="+claimId,
                        scripts: true,
                        callback: function(options, success, response, request)
                        {
                          if (response.responseText === "NoPrivilege"){
                            editClaimWin.close();
                          }
                        }
                      }
                    });
                    editClaimWin.on("destroy",function(){
                      claimDS.reload();
                    });
                    editClaimWin.resizable = false;
                    editClaimWin.show();
                  }else{
                    Ext.Msg.alert('提示信息','正在申请、已经通过审批或已经撤消的索赔，不能编辑。');
                  }
                } 
              }
            },"-",{
              text: '撤消',
              iconCls: 'cancel',
              handler : function(){
                var records = claimGrid.getSelectionModel().getSelections();
                if (records.length == 0) {
                  return false;
                }else{
                  if(records[0].get('auditing_status').indexOf('申请') < 0 && records[0].get('auditing_status').indexOf('撤消') < 0 ){
                    var orderNumber = records[0].get('order_number')
                    claimId = records[0].get('id');
                    Ext.MessageBox.confirm("提示","你确认要申请撤消订单号为： \""+orderNumber+"\" 的索赔吗？",function(btn){
                      if(btn=="yes"){
                        Ext.Ajax.request({
                          url : '/claim/applyToCancel?id=' + claimId,
                          success : function (result, request) {
                            claimDS.reload();
                          },
                          failure : function (result, request){
                            Ext.MessageBox.show({
                              title: '消息',
                              msg: "通讯失败，请从新操作",
                              buttons: Ext.MessageBox.OK,
                              icon: Ext.MessageBox.WARNING
                            });
                          },
                          method : 'GET'
                        });
                      }else{
                        //alert("no");
                      }
                    });
                  }else{
                    Ext.Msg.alert('提示信息','正处于申请状态或已经撤消的订单，不能撤消。');
                  }
                }
              }
            },'-',{
              text: '打印采购凭据',
              iconCls: 'print',
              handler : function(){
                var records = claimGrid.getSelectionModel().getSelections();
                if (records.length == 0) {
                  return false;
                }else{
                  if(records[0].get('deal_with_status') != '已撤消'){
                    claimId = records[0].get('id');
                    window.open('/test/purchase_order_print?id='+claimId,'_blank','width=0,height=0,toolbar=no,menubar=no,location=no');
                  }
                }
              }
            }]
        });
        
        //claimDS.load(privilegeJsonCallBack);
        claimDS.load();

        claimGrid.on('rowdblclick', function(gridPanel, rowIndex, e){
          claimId = claimDS.getAt(rowIndex).get('id');
          var claimNumber = claimDS.getAt(rowIndex).get('order_number');
          //claimDS.reload();
          claimDetailDS.removeAll();
          claimDetailDS.baseParams.claim_id = claimId;
          claimDetailDS.load();
          claimDetailGrid.setTitle("索赔："+claimNumber+"，的详细信息");
        });
        
        //右键
        claimGrid.on('rowcontextmenu', function(grid, rowIndex, e){
          claimId = claimDS.getAt(rowIndex).get('id');
          currentOrderNumber = claimDS.getAt(rowIndex).get('order_number');
          var auditingStatus = claimDS.getAt(rowIndex).get('auditing_status');
          var storeStatus = claimDS.getAt(rowIndex).get('store_status');
          returnedForClaimItem.setDisabled(true);
          if (auditingStatus.indexOf("通过撤消") > -1 || auditingStatus.indexOf("申请撤消") > -1){
            returnedForClaimItem.setDisabled(true);
          }else{
            returnedForClaimItem.setDisabled(false);
          }
          if(storeStatus == '入库完毕'){
            returnedForClaimItem.setDisabled(true);
          }
          e.preventDefault();
          rightClick.showAt(e.getXY());
        });
        //############ 订单-右键菜单 ##########
        var returnedForClaimItem = new Ext.menu.Item({
          text: '【索赔返库】',
          //iconCls: 'album',
          handler: rightMenuReturnedForClaimFn
        });

        function rightMenuReturnedForClaimFn(){
          newReturnedForClaimWin = new Ext.Window({
            layout: 'fit',
            width: 917,
            height: 483,
            closeAction: 'destroy',
            plain: true,
            modal: true,
            constrain:true,
            draggable: false,
            //modal: true,
            title: '索赔订单:\"'+currentOrderNumber+'\"转换为索赔返库订单',
            autoLoad: {
              url: "/claim_returned/newReturnedFromClaim?id="+claimId,
              scripts: true
            }
          });
          newReturnedForClaimWin.on("destroy",function(){
            claimDS.reload();
          });
          newReturnedForClaimWin.resizable = false;
          newReturnedForClaimWin.show();
        }
        
        var rightClick = new Ext.menu.Menu({
          items: [returnedForClaimItem]
        });


        //--------------------------索赔详细，双击后可显示数据----------------
        //索赔Grid Store Detail
        var claimDetailDS = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: '/claim/getClaimDetailsBalanceById'
          }),
          reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'product_name'
            },{
              name: 'product_number'
            },{
              name: 'spec'
            },{
              name: 'quantity',
              type: 'int'
            }, {
              name: 'unit_price',
              type: 'float'
            }, {
              name: 'amount',
              type: 'float'
            }, {
              name: 'is_suit',
              convert:function(value,record){
                if(value == "1"){
                  return "套装";
                }else if(value == "0"){
                  return "单品";
                }
              }
            },{
              name: 'balance_quantity',
              type: 'int'
            }, {
              name: 'description'
            }])
        });

        //生成索赔详细表的Grid的CM
        var claimDetailSM = new Ext.grid.CheckboxSelectionModel({singleSelect:true});
        var claimDetailCM = new Ext.grid.ColumnModel({defaults: {
            sortable: true,
            menuDisabled: false
          },columns:[new Ext.grid.RowNumberer(),claimDetailSM,{
              id: 'common',
              header: 'DB',
              dataIndex: 'id',
              width: 50
            },{
              header: '产品名称',
              dataIndex: 'product_name',
              width: 230
            },{
              header: '编号',
              dataIndex: 'product_number',
              width: 70
            },{
              header: '规格',
              dataIndex: 'spec',
              width: 50
            },{
              header: '数量',
              dataIndex: 'quantity',
              align: 'right',
              width: 50
            },{
              header: '单价',
              dataIndex: 'unit_price',
              align: 'right',
              renderer: moneyPrivilegeRender,
              width: 50
            },{
              header: '总价',
              dataIndex: 'amount',
              align: 'right',
              renderer: moneyPrivilegeRender,
              width: 70
            },{
              header: '套装或单品',
              dataIndex: 'is_suit',
              width: 70
            },{
              header: '索赔与返库差比',
              dataIndex: 'balance_quantity',
              width: 100
            },{
              header: '备注',
              dataIndex: 'description',
              width: 150
            }
          ]});
        //生成要订单的产品的Grid
        var claimDetailGrid = new Ext.grid.GridPanel({
          title:'订单详细列表',
          store: claimDetailDS,
          cm: claimDetailCM,
          sm: claimDetailSM,
          loadMask: true,
          width: screenWidth-175,
          height: screenHeight-640,
          frame: true
        });

        //总的panel
        var workbenchPanel = new Ext.Panel({
          width: screenWidth-175,
          height: screenHeight-170,
          frame:false,
          layout:'table',
          layoutConfig: {columns:1},
          defaults:{margins:'5 5 5 5'},
          items:[queryFormPanel,claimGrid,claimDetailGrid]
        });
        workbenchPanel.render("workbench_panel");
      })
    </script>
  </head>
  <body>
    <div id="workbench_panel"></div>
  </body>
</html>